package speelotheek.views;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.BoxLayout;
import javax.swing.border.TitledBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextField;
import javax.swing.JButton;

import speelotheek.configs.Config;
import speelotheek.models.Lid;

public class CustomerInfo extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3180064831961986767L;
	
	private String nummer;
	
	private JTextField txtNummer;
	private JTextField txtNaam;
	private JTextField txtAdres;
	private JTextField txtPostcode;
	private JTextField txtWoonplaats;
	private JTextField txtEmail;
	private JTextField txtTelefoon;
	private JButton btnWijzigen;
	private JButton btnOpslaan;
	private JButton btnVerlengen;
	private JButton btnKinderen;
	
	private boolean _fieldStatus;
	
	private Lid lid;
	private Config config;
	
	private ArrayList<String> customerErrors;
	
	private Calendar cal;

	/**
	 * Create the dialog.
	 */
	public CustomerInfo(final String nummer) {
		this.nummer = nummer;
		
		setBounds(100, 100, 610, 340);
		setTitle("Lid - Meer Info");
		setLocationRelativeTo(null);
		setModal(true);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
		
		config = new Config();
		
		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(null, "Lid Info", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		getContentPane().add(panel);
		
		JLabel lblNummer = new JLabel("Nummer:");
		
		JLabel lblNaam = new JLabel("Naam:");
		
		JLabel lblAdres = new JLabel("Adres:");
		
		JLabel lblPostcode = new JLabel("Postcode:");
		
		JLabel lblWoonplaats = new JLabel("Woonplaats:");
		
		JLabel lblTelefoon = new JLabel("Telefoon:");
		
		JLabel lblEmail = new JLabel("Email:");
		
		txtNummer = new JTextField();
		txtNummer.setEnabled(false);
		txtNummer.setColumns(10);
		
		txtNaam = new JTextField();
		txtNaam.setEnabled(false);
		txtNaam.setColumns(10);
		
		txtAdres = new JTextField();
		txtAdres.setEnabled(false);
		txtAdres.setColumns(10);
		
		txtPostcode = new JTextField();
		txtPostcode.setEnabled(false);
		txtPostcode.setColumns(10);
		
		txtWoonplaats = new JTextField();
		txtWoonplaats.setEnabled(false);
		txtWoonplaats.setColumns(10);
		
		txtEmail = new JTextField();
		txtEmail.setEnabled(false);
		txtEmail.setColumns(10);
		
		txtTelefoon = new JTextField();
		txtTelefoon.setEnabled(false);
		txtTelefoon.setColumns(10);
		
		_addCustomerInfo();
		
		btnWijzigen = new JButton("Wijzigen");
		btnWijzigen.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(_fieldStatus) {
					_restoreFieldValues();
					_changeFields(false);
					btnWijzigen.setText("Wijzigen");
					btnOpslaan.setEnabled(false);
				} 
				else {
					_changeFields(true);
					btnWijzigen.setText("Terugzetten");
					btnOpslaan.setEnabled(true);
				}
			}
		});
		
		DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
		Date eindlidmaatschap = lid.getEindlidmaatschap();
		Date today = new Date();
		cal = Calendar.getInstance();
		if(eindlidmaatschap == null) {
			cal.setTime(today);
		}
		else {
			if(today.after(eindlidmaatschap)) {
				cal.setTime(today);
			}
			else {
				cal.setTime(eindlidmaatschap);
			}
		}
		cal.add(Calendar.YEAR, config.MEMBERSHIP_DURATION);
		final String datum = df.format(cal.getTime());
		
		btnVerlengen = new JButton("Verlengen");
		btnVerlengen.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg2) {
				String msgOne = "Weet u zeker dat u dit lidmaatschap wilt verlengen? \n\n Nieuwe Einddatum: "+datum;
				int confirmChange = JOptionPane.showConfirmDialog(null, msgOne, "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
				switch(confirmChange) {
					case JOptionPane.YES_OPTION:
						try {
							_extendMembership();
							String msgThree = "Lidmaatschap succesvol verlengd";
							JOptionPane.showMessageDialog(null, msgThree, "Succes", JOptionPane.INFORMATION_MESSAGE);
						} catch (Exception e) {
							String msgTwo = "Database Error\n\n Neem contact op met de beheerder als die probleem zich blijft voordoen.";
							JOptionPane.showMessageDialog(null, msgTwo, "Error", JOptionPane.ERROR_MESSAGE);
							return;
						}
						break;
					case JOptionPane.NO_OPTION:
						break;
				}							
			}
		});
		
		btnKinderen = new JButton("Kinderen");
		btnKinderen.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				Childeren childeren = new Childeren(nummer);
				childeren.setVisible(true);
			}
		});
		
		btnOpslaan = new JButton("Opslaan");
		btnOpslaan.setEnabled(false);
		btnOpslaan.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg1) {
				String msgOne = "Weet u zeker dat u dit lid wilt wijzigen?";
				int confirmChange = JOptionPane.showConfirmDialog(null, msgOne, "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
				switch(confirmChange) {
					case JOptionPane.YES_OPTION:	
						try {					
							_changeCustomer();
							String msgThree = "Lid succesvol gewijzigd";
							JOptionPane.showMessageDialog(null, msgThree, "Succes", JOptionPane.INFORMATION_MESSAGE);
						} 
						catch (Exception ex) {
							String msgTwo = "Database Error\n\n Neem contact op met de beheerder als die probleem zich blijft voordoen.";
							JOptionPane.showMessageDialog(null, msgTwo, "Error", JOptionPane.ERROR_MESSAGE);
							return;
						}	
						break;
					case JOptionPane.NO_OPTION:
						break;
				}							
				_changeFields(false);
				btnWijzigen.setText("Wijzigen");
				btnOpslaan.setEnabled(false);
			}
		});
		
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addGap(45)
					.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
						.addComponent(lblTelefoon)
						.addComponent(lblEmail)
						.addComponent(lblNummer)
						.addComponent(lblPostcode)
						.addComponent(lblWoonplaats)
						.addComponent(lblAdres)
						.addComponent(lblNaam))
					.addGap(18)
					.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
						.addGroup(Alignment.TRAILING, gl_panel.createSequentialGroup()
							.addComponent(txtNummer, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.RELATED, 317, Short.MAX_VALUE)
							.addComponent(btnKinderen))
						.addGroup(Alignment.TRAILING, gl_panel.createSequentialGroup()
							.addComponent(txtTelefoon, GroupLayout.PREFERRED_SIZE, 103, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.RELATED, 304, Short.MAX_VALUE)
							.addComponent(btnOpslaan))
						.addGroup(Alignment.TRAILING, gl_panel.createSequentialGroup()
							.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING, false)
								.addComponent(txtAdres, Alignment.LEADING)
								.addComponent(txtWoonplaats, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)
								.addComponent(txtNaam, Alignment.LEADING)
								.addComponent(txtEmail, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 156, GroupLayout.PREFERRED_SIZE))
							.addPreferredGap(ComponentPlacement.RELATED, 241, Short.MAX_VALUE)
							.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
								.addComponent(btnWijzigen)
								.addComponent(btnVerlengen)))
						.addComponent(txtPostcode, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addContainerGap())
		);
		gl_panel.setVerticalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNummer)
						.addComponent(txtNummer, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(btnKinderen))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNaam)
						.addComponent(txtNaam, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(btnVerlengen))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblAdres)
						.addComponent(txtAdres, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblPostcode)
						.addComponent(txtPostcode, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblWoonplaats)
						.addComponent(txtWoonplaats, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblEmail)
						.addComponent(txtEmail, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(btnWijzigen))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblTelefoon)
						.addComponent(txtTelefoon, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(btnOpslaan))
					.addContainerGap(157, Short.MAX_VALUE))
		);
		panel.setLayout(gl_panel);
	}
	
	private void _addCustomerInfo() 
	{		
		int id = Integer.parseInt(nummer);
		lid = Lid.getLid(id);
		
		String naam = lid.getNaam();
		String adres = lid.getAdres();
		String postcode = lid.getPostcode();
		String woonplaats = lid.getWoonplaats();
		String email = lid.getEmail();
		String telefoon = lid.getTelefoon();
		
		txtNummer.setText(nummer);
		txtNaam.setText(naam);
		txtAdres.setText(adres);
		txtPostcode.setText(postcode);
		txtWoonplaats.setText(woonplaats);
		txtEmail.setText(email);
		txtTelefoon.setText(telefoon);
	}
	
	private void _changeFields(boolean en)
	{
		txtNaam.setEnabled(en);
		txtAdres.setEnabled(en);
		txtPostcode.setEnabled(en);
		txtWoonplaats.setEnabled(en);
		txtEmail.setEnabled(en);
		txtTelefoon.setEnabled(en);
		
		_fieldStatus = en;
	}
	
	private void _restoreFieldValues()
	{
		String naam = lid.getNaam();
		String adres = lid.getAdres();
		String postcode = lid.getPostcode();
		String woonplaats = lid.getWoonplaats();
		String email = lid.getEmail();
		String telefoon = lid.getTelefoon();

		txtNaam.setText(naam);
		txtAdres.setText(adres);
		txtPostcode.setText(postcode);
		txtWoonplaats.setText(woonplaats);
		txtEmail.setText(email);
		txtTelefoon.setText(telefoon);
	}
	
	private void _changeCustomer() throws Exception
	{		
		// Alle text in de textfields ophalen
		String naam = txtNaam.getText();
		String adres = txtAdres.getText();
		String postcode = txtPostcode.getText();
		String woonplaats = txtWoonplaats.getText();
		String email = txtEmail.getText();
		String telefoon = txtTelefoon.getText();
		
		customerErrors = new ArrayList<String>();
		
		if(naam.isEmpty()) {
			customerErrors.add("U heeft geen naam ingevuld");
		}
		if(adres.isEmpty()) {
			customerErrors.add("U heeft geen adres ingevuld");
		}
		if(postcode.isEmpty()) {
			customerErrors.add("U heeft geen postcode ingevuld");
		}
		if(woonplaats.isEmpty()) {
			customerErrors.add("U heeft geen woonplaats ingevuld");
		}
		if(email.isEmpty()) {
			customerErrors.add("U heeft geen email ingevuld");
		}
		if(isValidEmail(email) == false) {
			customerErrors.add("U heeft geen geldig email adres ingevuld");
		}
		if(telefoon.isEmpty()) {
			customerErrors.add("U heeft geen telefoon nummer ingevuld");
		}
		
		telefoon = telefoon.replaceAll("[^0-9]", "");
		if(telefoon.length() != 10) {
			customerErrors.add("U heeft geen geldig telefoon nummer ingevuld");
		}
		
		if(customerErrors.isEmpty() != true) {
			throw new Exception("Errors on inputfields");
		}
		
		int id = Integer.parseInt(nummer);
		
		lid.setNummer(id);
		lid.setNaam(naam);
		lid.setAdres(adres);
		lid.setPostcode(postcode);
		lid.setWoonplaats(woonplaats);
		lid.setEmail(email);
		lid.setTelefoon(telefoon);	
		lid.updateCustomer();
	}
	
	private void _extendMembership() throws Exception
	{
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(lid.getEindlidmaatschap());
		calendar.add(Calendar.YEAR, config.MEMBERSHIP_DURATION);
		
		lid.setEindlidmaatschap(new java.sql.Date(calendar.getTimeInMillis()));
		lid.updateCustomer();
	}
	
	private boolean isValidEmail(String email)
	{
		String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		Pattern pattern = Pattern.compile(EMAIL_PATTERN);
		Matcher matches = pattern.matcher(email);
		return matches.matches();
	}
}
